import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/data_fetcher.dart';

class CourseReviewReplyPageLogic extends ChangeNotifier {
  final int reviewId;
  final int courseId;
  final int ratting;
  final String reviewUser;
  final String reviewContent;
  final int? replyId;
  final String? replyContent;

  late final TextEditingController controller;
  late final FocusNode focusNode;

  CourseReviewReplyPageLogic({
    required this.reviewId,
    required this.courseId,
    required this.ratting,
    required this.reviewUser,
    required this.reviewContent,
    this.replyId,
    this.replyContent,
  });

  void init() {
    controller = TextEditingController();
    focusNode = FocusNode();

    controller.text = replyContent ?? '';
  }

  Future<String?> replyReview() async {
    final newReply = controller.text.trim();
    if (newReply.isEmpty) {
      EasyLoading.showError(AppStrings.contentCannotBeEmpty);
      return null;
    }

    if (newReply == replyContent) {
      return '';
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.businessApi.replyCourseReview(
        courseId,
        reviewId,
        newReply,
      );
      EasyLoading.dismiss();
      if (response.code == 0) {
        EasyLoading.showSuccess(AppStrings.replySuccess);
        return newReply;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return null;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return null;
    }
  }
}
